package com.batch_demo.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelUtil {
    public static List<Map<String, String>> read(String filePath) throws IOException {
        List<Map<String, String>> result = new ArrayList<>();


        InputStream inputStream = new FileInputStream(filePath);
        Workbook workbook = new XSSFWorkbook(inputStream);

        int numberOfSheets = workbook.getNumberOfSheets();

        for (int i = 0; i < numberOfSheets; i ++) {
            if (i > 0) {
                continue;
            }
            Sheet sheet = workbook.getSheetAt(i);
            int lastRowNum = sheet.getLastRowNum();
            int size = lastRowNum + 1;

            List<String> titles = new ArrayList<String>();

            for (int j = 0; j < size; j ++) {
                Row row = sheet.getRow(j);
                if (null == row) {
                    continue;
                }

                short lastCellNum = row.getLastCellNum();
                if (j == 0) {
                    for (int k = 0; k < lastCellNum; k ++) {
                        Cell cell = row.getCell(k);
                        titles.add(cell.toString());
                    }
                }else {//其他行是数据行
                    Map<String, String> rowMap = new HashMap<String, String>();
                    for (int k = 0; k < titles.size(); k++) {
                        Cell cell = row.getCell(k);
                        String key = titles.get(k);
                        String value = null;
                        if (cell != null) {
                            value = cell.toString();
                        }
                        rowMap.put(key, value);
                    }
                    result.add(rowMap);
                }
            }
        }

        return result;
    }

    public static void main(String[] args) throws IOException {
        List<Map<String, String>> mapList = ExcelUtil.read("/Users/zhangyingxuan/Downloads/20180107/3-2017年Q4考核（普通员工有等级有系数）37人——20180106.xlsx");
        for (Map<String, String> map : mapList) {
//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                System.out.print(entry.getKey() + " -> " + entry.getValue()+ "; ");
//            }
            String m1 = map.get("序号");
            String m2 = map.get("【等级】");
            String m3 = map.get("【调整后系数】");
            System.out.println(m1 + "\t" + m2 + "\t" + "\t" + m3);
        }
    }
}
